package com.bms.admin.config.exception;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.bms.auth.exception.ErrorTokenException;
import com.bms.auth.exception.ExpiredTokenException;
import com.bms.auth.exception.NoLoginException;
import com.bms.auth.exception.UnauthorizedException;
import com.bms.common.base.common.bean.Result;
import com.bms.common.base.common.exception.BusinessException;
import com.bms.common.base.web.BaseController;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler extends BaseController {
	
	 private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	 /**
	   * 400 - Bad Request
	   */
	  @ResponseStatus(HttpStatus.BAD_REQUEST)
	  @ExceptionHandler(MissingServletRequestParameterException.class)
	  public Result handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
	    logger.error("缺少请求参数", e);
	    return fail("required_parameter_is_not_present", "-1");
	  }

	  /**
	   * 400 - Bad Request
	   */
	  @ResponseStatus(HttpStatus.BAD_REQUEST)
	  @ExceptionHandler(HttpMessageNotReadableException.class)
	  public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
	    logger.error("参数解析失败", e);
	    return fail("could_not_read_json", "-2");
	  }

	  /**
	   * 400 - Bad Request
	   */
	  @ResponseStatus(HttpStatus.BAD_REQUEST)
	  @ExceptionHandler(MethodArgumentNotValidException.class)
	  public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
	    logger.error("参数验证失败", e);
	    BindingResult result = e.getBindingResult();
	    FieldError error = result.getFieldError();
	    String field = error.getField();
	    String code = error.getDefaultMessage();
	    String message = String.format("%s:%s", field, code);
	    return fail(message, "-3");
	  }

	  /**
	   * 400 - Bad Request
	   */
	  @ResponseStatus(HttpStatus.BAD_REQUEST)
	  @ExceptionHandler(BindException.class)
	  public Result handleBindException(BindException e) {
	    logger.error("参数绑定失败", e);
	    BindingResult result = e.getBindingResult();
	    FieldError error = result.getFieldError();
	    String field = error.getField();
	    String code = error.getDefaultMessage();
	    String message = String.format("%s:%s", field, code);
	    return fail(message, "-4");
	  }

	  /**
	   * 400 - Bad Request
	   */
	  @ResponseStatus(HttpStatus.BAD_REQUEST)
	  @ExceptionHandler(ConstraintViolationException.class)
	  public Result handleServiceException(ConstraintViolationException e) {
	    logger.error("参数验证失败", e);
	    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
	    ConstraintViolation<?> violation = violations.iterator().next();
	    String message = violation.getMessage();
	    return fail("parameter:" + message, "-5");
	  }

	  /**
	   * 400 - Bad Request
	   */
	  @ResponseStatus(HttpStatus.BAD_REQUEST)
	  @ExceptionHandler(ValidationException.class)
	  public Result handleValidationException(ValidationException e) {
	    logger.error("参数验证失败", e);
	    return fail("validation_exception", "-6");
	  }

	  /**
	   * 405 - Method Not Allowed
	   */
	  @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	  @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	  public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
	    logger.error("不支持当前请求方法", e);
	    return fail("request_method_not_supported", "-7");
	  }

	  /**
	   * 415 - Unsupported Media Type
	   */
	  @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	  @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	  public Result handleHttpMediaTypeNotSupportedException(Exception e) {
	    logger.error("不支持当前媒体类型", e);
	    return fail("content_type_not_supported", "-8");
	  }

	  /**
	   * 500 - Internal Server Error
	   */
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(Exception.class)
	  public Result handleException(Exception e) {
	    logger.error("通用异常", e);
	    return fail("通用异常：" + e.getMessage(), "-10");
	  }

	  /**
	   * 操作数据库出现异常:名称重复，外键关联
	   */
	  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	  @ExceptionHandler(DataIntegrityViolationException.class)
	  public Result handleException(DataIntegrityViolationException e) {
	    logger.error("操作数据库出现异常:", e);
	    return fail("操作数据库出现异常：字段重复、有外键关联等", "-11");
	  }
	  
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(DuplicateKeyException.class)
	  public Result handleException(DuplicateKeyException e) {
		 String msg =  e.getCause().getMessage();
		 if(msg.contains("ONLY_NO_CARD")){  //号码牌重复
			 String cardNo =  msg.split("-")[0].split("'")[1];
			 logger.error("号码牌重复:", msg);
			 return fail(cardNo+"号码牌重复！", "-11");
		 }
	    logger.error("操作数据库出现异常:", e);
	    return fail("请勿重复提交", "-11");
	  }
	  
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(BusinessException.class)
	  public Result handleException(BusinessException e) {
	    logger.error("业务异常", e.getLocalMessage().getMessage());
	    return fail(e.getLocalMessage().getMessage(),e.getLocalMessage().getMessageCode());
	  }
	  
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(ErrorTokenException.class)
	  public Result handleException(ErrorTokenException e) {
	    logger.error("Error Token", e.getCode(),e.getMessage());
	    return fail(e.getMessage(),e.getCode());
	  }
	  
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(ExpiredTokenException.class)
	  public Result handleException(ExpiredTokenException e) {
	    logger.error("Expired Token", e.getCode(),e.getMessage());
	    return fail(e.getMessage(),e.getCode());
	  }
	  
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(UnauthorizedException.class)
	  public Result handleException(UnauthorizedException e) {
	    logger.error("UnauthorizedException", e.getCode(),e.getMessage());
	    return fail(e.getMessage(),e.getCode());
	  }
	  
	  @ResponseStatus(HttpStatus.OK)
	  @ExceptionHandler(NoLoginException.class)
	  public Result handleException(NoLoginException e) {
	    logger.error("No Login", e.getCode(),e.getMessage());
	    return fail(e.getMessage(),e.getCode());
	  }
	  
	}

